#!/bin/bash

# 飞书Webhook URL
FEISHU_WEBHOOK_URL="https://open.feishu.cn/open-apis/bot/v2/hook/42de13af-59a8-4c48-9560-5ac5581020b3"

# Jenkins构建信息
JOB_NAME="$JOB_NAME"
BUILD_NUMBER="$BUILD_NUMBER"
BUILD_URL="$BUILD_URL"
# 获取上一个命令的退出状态，用于判断构建结果
BUILD_RESULT=""

JOB_URL="${JENKINS_URL}job/${JOB_NAME}"
echo "job_url:" $JOB_URL

getBuildState() {
    buildNr=$1
    result=$2
    user=apiuser
    passwd=5ac5581020b3
    curl -u $user:$passwd ${JOB_URL}/${buildNr}/api/json | grep -Po $result
}

state=$(getBuildState $BUILD_NUMBER '"result":\s*"\K\w+')
echo "state:" ${state}
echo "======"

if [[ "${state}" == "SUCCESS" ]]; then
    BUILD_RESULT="成功"
elif [[ "${state}" == "ABORTED" ]]; then
    BUILD_RESULT="取消"
else
    BUILD_RESULT="失败"
fi

BUILD_TIMESTAMP=$(date '+%Y-%m-%d %H:%M:%S')

# 构建消息内容
PAYLOAD="{
    \"msg_type\": \"interactive\",
    \"card\": {
        \"config\": {
            \"wide_screen_mode\": true
        },
        \"header\": {
            \"title\": {
                \"content\": \"🤖️ Jenkins构建通知\",
                \"tag\": \"plain_text\"
            }
        },
        \"elements\": [
            {
                \"tag\": \"div\",
                \"text\": {
                    \"content\": \"**项目：** $JOB_NAME\\n**构建号：**$BUILD_NUMBER\\n**远程分支：**$GIT_BRANCH\\n**构建结果：** $BUILD_RESULT\\n**构建时间：**$BUILD_TIMESTAMP\",
                    \"tag\": \"lark_md\"
                }
            },
            {
                \"tag\": \"action\",
                \"actions\": [
                    {
                        \"tag\": \"button\",
                        \"text\": {
                            \"content\": \"查看详情\",
                            \"tag\": \"plain_text\"
                        },
                        \"type\": \"primary\",
                        \"url\": \"$BUILD_URL\"
                    }
                ]
            }
        ]
    }
}"

# 发送请求到飞书
curl -X POST -H "Content-Type: application/json" -d "$PAYLOAD" "$FEISHU_WEBHOOK_URL"
